﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AisEncodingLib
{
	public static class AisEncoder
	{
		/// <summary>
		/// 6Bit 编码2进制字符串转6Bit AScii 编码字符串
		/// </summary>
		/// <param name="bitString"></param>
		/// <returns></returns>
		public static string Encode6Bit(string bitString)
		{
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < bitString.Length; i += 6)
			{
				string chunk = bitString.Substring(i, Math.Min(6, bitString.Length - i));
				int val = Convert.ToInt32(chunk, 2);
				int code = val + 48;
				if (code > 87) code += 8;
				sb.Append((char)code);
			}
			return sb.ToString();
		}

		/// <summary>
		/// 计数校验
		/// </summary>
		/// <param name="sentence"></param>
		/// <returns></returns>
		public static string CalculateChecksum(string sentence)
		{
			int checksum = 0;
			foreach (char c in sentence)
				checksum ^= Convert.ToByte(c);
			return checksum.ToString("X2");
		}

		/// <summary>
		/// 封装NMEA
		/// </summary>
		/// <param name="payload"></param>
		/// <param name="fillBits"></param>
		/// <returns></returns>
		public static string WrapNmea(string payload, int fillBits = 0)
		{
			string sentence = $"!AIVDM,1,1,,A,{payload},{fillBits}";
			string checksum = CalculateChecksum(sentence.Substring(1));
			return $"{sentence}*{checksum}";
		}

		/// <summary>
		/// 封装NMEA
		/// </summary>
		/// <param name="packNUm"></param>
		/// <param name="nowPack"></param>
		/// <param name="payload"></param>
		/// <param name="fillBits"></param>
		/// <returns></returns>
		public static string WrapNmea(string packNUm,string nowPack, string payload, int fillBits = 0)
		{
			string sentence = $"!AIVDM,{packNUm},{nowPack},,A,{payload},{fillBits}";
			string checksum = CalculateChecksum(sentence.Substring(1));
			return $"{sentence}*{checksum}";
		}

        /// <summary>
		/// 字符串转为6Bit 编码2进制字符串
		/// </summary>
		public static string EncodeString6bit(string text, int maxChars)
		{
			string s = text.ToUpper().PadRight(maxChars, '@');
			StringBuilder bits = new StringBuilder();
			foreach (char c in s)
			{
				int val;
				if (c >= '!' && c <= '?') val = c;
				else if (c >= '@' && c <= '_') val = c - 'A' + 1;
				else val = 32; // blank
				bits.Append(Convert.ToString(val, 2).PadLeft(6, '0'));
			}
			return bits.ToString();
		}
	}
}
